#!/usr/bin/env bash
SELFDIR=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)

function init()
{
    #   source init.bash plan@view
    local env_label="$1"
    local env_file=$(echo  "${env_label}" | sed 's#@# #g' | awk '{print $1}')
    local env_slice=$(echo "${env_label}" | sed 's#@# #g' | awk '{print $2}')

    if [[ "${env_slice}" == "" ]]; then
        env_slice="dev"
    fi

    #echo "env_label: ${env_label}"
    #echo "env_file:  ${env_file}"
    #echo "env_slice: ${env_slice}"

    if [[ ! -f "${SELFDIR}/${env_file}" ]]; then
        return 0
    fi

    while read line; do
        if [[ "${line}" =~ ^\s*#.*$ ]]; then
            continue
        fi

        local module_label=$(echo "${line}" | awk '{print $1}')
        local module_slice_items=$(echo "${line}"  | awk '{print $2}' | sed 's#:# #g')

        #   匹配环境切片
        local module_matched="no"
        for slice_item in ${module_slice_items}; do
            if [[ "${slice_item}" == "${env_slice}" ]]; then
                module_matched="yes"
                break
            fi
        done

        #   如果切片不匹配，那么跳过该模块
        if [[ "${module_matched}" == "no" ]]; then
            continue
        fi

        #   模块没部署
        local module_installed_flag_file="${SELFDIR}/${module_label}/.pkgr-installed"
        if [[ ! -f "${module_installed_flag_file}" ]]; then
            echo    "[FAIL] ${module_label} : The module is not complete the installation: '${module_installed_flag_file}'"
            continue
        fi

        #   模块没 setup 文件
        local module_setup_file="${SELFDIR}/${module_label}/setup.bash"
        if [[ ! -f "${module_setup_file}" ]]; then
            echo    "[FAIL] ${module_label} : The setup file is missing: '${module_setup_file}'"
            continue
        fi

        #   加载 setup 文件失败
        # echo "[init] ${module_label}"
        source "${module_setup_file}"
        RESULT=$?
        if [[ ${RESULT} -ne 0 ]]; then
            echo    "[FAIL] ${module_label} : Loading setup file failed(${RESULT}): '${module_setup_file}'"
            break
        fi
    done < "${SELFDIR}/${env_file}"

    return 0
}

init  "$@"
export PS1="\e[30;47m\w \e[0m\n# "
